# if condition:
# statement
# ---optional!---
# elif condition:
# statement
# elif condition:
# statement
# else:
# statement
=90; exam2=85
exam1if(exam1>=90) and (exam2>=90):
print('Excellent!')
3 Control Flows
3.0.0.1 - Control statements in Python
- Conditional Constructs : if
- Loops : for, while
3.1 Statements & Comments
3.2 if Conditionals
if(exam1>=90) | (exam2>=90):
print('Good')
Good
=10
aif a>10:
print("a>10")
else:
print("a=10")
a=10
# Exercise 1
=[1,2,3,4,6,7,9]
a=a.copy()
b
b.sort()
if a==b:
print("a is sorted")
else:
print("a is not sorted")
a is sorted
# Exercise2
=[1,2,3,4,5,6,7,8]
x
=x.copy()
x_sort
x.sort()
=len(x_sort)
len_x=(x_sort[int(len(x_sort)/2-1)]+x_sort[int(len(x_sort)/2)])/2
mid_even=x_sort[int(len(x_sort)//2)]
mid_odd
if len(x_sort)%2==0:
print("n={}이고, 중간값은 {}입니다.".format(len_x,mid_even))
elif len(x_sort)%2==1:
print("n={}이고, 중간값은 {}입니다.".format(len_x,mid_odd))
else :
print("중간값을 산출할 수 없습니다.")
n=8이고, 중간값은 4.5입니다.
3.3 Loops - for loop
# for interating_var in iterable:
# statements
# exercise 3
=input("When you enter...")
a=int(a)
a_intprint("Input a number: "+a,
"The output will be...",
="\n")
sepfor i in range(1,10):
print(a+" x "+str(i)+" = "+str(a_int*i))
Input a number: 99
The output will be...
99 x 1 = 99
99 x 2 = 198
99 x 3 = 297
99 x 4 = 396
99 x 5 = 495
99 x 6 = 594
99 x 7 = 693
99 x 8 = 792
99 x 9 = 891
# exercise 4
=0
sum_even=0
sum_oddfor i in range(10001):
if i%2==0:
+=i
sum_evenelse:sum_odd+=i
print(sum_even,
sum_odd,+sum_odd,
sum_even='\n') sep
25005000
25000000
50005000
# exercise 5
=[1,1]
fibonaccifor i in range(10):
+fibonacci[i+1])
fibonacci.append(fibonacci[i]print(
fibonacci,sum(fibonacci),
='\n'
sep )
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]
376
# exercise 6
=input("When you enter alpha-num string...")
a=list()
letter_index=list()
digits_index=list()
non_indexprint(
"Sample Data : "+a,
"The output will be...",
='\n'
sep
)for i in range(0,len(a)):
if a[i].isalpha():
letter_index.append(i)elif a[i].isnumeric():
digits_index.append(i)else: non_index.append(i)
print(
"Letters {} at {}".format(len(letter_index),letter_index),
"Digits {} at {}".format(len(digits_index),digits_index),
"And there are {} at {} which are NOT alphanumeric".format(len(non_index),non_index),
='\n'
sep )
Sample Data : sample asdfl11231,2,1,3.2 21
The output will be...
Letters 11 at [0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11]
Digits 11 at [12, 13, 14, 15, 16, 18, 20, 22, 24, 27, 28]
And there are 7 at [6, 17, 19, 21, 23, 25, 26] which are NOT alphanumeric